package com.gton.config;

import feign.Logger;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @description: OpenFeign进阶配置
 * @author: GuoTong
 * @createTime: 2022-12-02 20:49
 * @since JDK 1.8 OR 11
 **/
@Configuration
public class OpenFeignConfig {

    /**
     * Description:
     * NONE：默认，不显示任何日志；
     * BASIC: 仅记录请求方法、URL、响应状态码及执行时间；
     * HEADERS：除了BASIC中定义的信息之外，还有请求头和响应头信息；
     * FULL：除了HEADERS中定义的信息之外，还有请求的正文和响应数据。
     *
     * @date: 2022-12-02 20:50:35
     */
    @Bean
    Logger.Level feignLogLevel() {
        return Logger.Level.FULL;
    }


    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            // 获取请求进入的数据
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            if (requestAttributes != null) {
                // fegin调用前的原始请求
                HttpServletRequest request = requestAttributes.getRequest();
                if (request != null) {
                    String cookie = request.getHeader("Cookie");
                    // 添加cookie
                    template.header("Cookie", cookie);
                    // 添加Content-Type
                    String contentType = request.getContentType();
                    template.header("Content-Type", contentType);
                }
            }

        };
    }
}